package me.shurufa.net;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;

import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.List;

/**
 * 兑换积分使用的Client 需要自己加Js接口或者与服务器js接口联调
 * 从而同步积分
 *
 * @FileName: me.shurufa.net.TencentWebViewClient.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-19 16:18
 */
@SuppressLint("SetJavaScriptEnabled")
public class TencentWebViewClient extends WebViewClient {

    private List<String> urlStrings;
    private WebView mWebView;

    public TencentWebViewClient(List<String> urlStrings,WebView webView) {
        this.urlStrings = urlStrings;
        this.mWebView = webView;
    }

    @Override
    public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
        webView.getSettings().setJavaScriptEnabled(true);
        super.onPageStarted(webView, s, bitmap);
    }

    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if( url.startsWith("http:") || url.startsWith("https:") ) {
            urlStrings.add(url);
            return false;
        }
        return false;
    }



    @Override
    public void onPageFinished(WebView view, String url) {
        view.getSettings().setJavaScriptEnabled(true);
        if(!view.getSettings().getLoadsImagesAutomatically()) {
            view.getSettings().setLoadsImagesAutomatically(true);
        }
        addImageClickListner();
    }

    @Override
    public void onReceivedError(WebView webView, int i, String s, String s1) {
        super.onReceivedError(webView, i, s, s1);
    }


    /**
     * 此方法仅为样例 在webView中点击<img 时支持调用本地java方法
     */
    private void addImageClickListner() {
        if (mWebView!=null) {
            mWebView.loadUrl("javascript:(function(){" +
                    "var objs = document.getElementsByTagName(\"img\"); " +
                    "for(var i=0;i<objs.length;i++)  " +
                    "{"
                    + "    objs[i].onclick=function()  " +
                    "    {  "
                    + "        window.imagelistner.openImage(this.src);  " +
                    "    }  " +
                    "}" +
                    "})()");
        }
    }
}